package com.mingren.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingren.api.aliyunai.AiPictureToMp4;
import com.mingren.api.aliyunai.AliYunAiApi;
import com.mingren.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.mingren.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.mingren.api.aliyunai.modelPictureToMp4.CreateOutMp4TaskRequest;
import com.mingren.api.aliyunai.modelPictureToMp4.CreateOutMp4askResponse;
import com.mingren.constant.UserConstant;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import com.mingren.exception.ThrowUtils;
import com.mingren.manager.CosManager;
import com.mingren.manager.upload.FilePictureUpload;
import com.mingren.manager.upload.PictureUploadTemplate;
import com.mingren.manager.upload.UrlPictureUpload;
import com.mingren.mapper.PictureMapper;
import com.mingren.model.domain.Picture;
import com.mingren.model.domain.Space;
import com.mingren.model.domain.User;
import com.mingren.model.dto.file.UploadPictureResult;
import com.mingren.model.dto.pictureRequest.*;
import com.mingren.model.enums.PictureReviewStatusEnum;
import com.mingren.model.vo.PictureVO;
import com.mingren.model.vo.UserVO;
import com.mingren.service.PictureService;
import com.mingren.service.SpaceService;
import com.mingren.service.UserService;
import com.mingren.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ROG
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-02-27 14:57:14
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private CosManager cosManager;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private AiPictureToMp4 aiPictureToMp4;
    /**
     * 编程式事务
     */
    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 校验图片数据
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        //1、判空
        ThrowUtils.throwIf(picture == null, ErrorCode.NULL_ERROR, "请求参数为空");
        //2、从对象取值并校验数据
        Long id = picture.getId();
        ThrowUtils.throwIf(ObjUtil.isEmpty(id), ErrorCode.NULL_ERROR, "请求参数为空");
        String url = picture.getUrl();
        // 如果传递了 url，才校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        String introduction = picture.getIntroduction();
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 上传图片
     *
     * @param inputSource          : 文件流 -> 模板设计模式 区分链接和文件上传图片
     * @param pictureUploadRequest : 图片上传/修改请求体
     * @param loginUser            : 当前登录用户
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH);
        //上传至私有空间 -> 校验空间是否存在；如果存在，还要校验是否有空间权限，仅空间的管理员才能上传
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            //查询空间
            Space oldSpace = spaceService.getById(spaceId);
            ThrowUtils.throwIf(oldSpace == null, ErrorCode.NULL_ERROR, "该空间不存在");
            //如果存在校验是否有空间权限
            // Long userId = oldSpace.getUserId();
            // ThrowUtils.throwIf(!Objects.equals(userId, loginUser.getId()), ErrorCode.NO_AUTH, "无权限上传至该空间");
            //todo 检验额度
            //获得当前的图片数量‘
            Long totalCount = oldSpace.getTotalCount();
            //获取 最大的图片数量
            Long maxCount = oldSpace.getMaxCount();
            //判断
            if (totalCount >= maxCount) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "空间图片条数不足");
            }
            //获得当前的图片占用的总大小
            Long totalSize = oldSpace.getTotalSize();
            //获取空间最大容量
            Long maxSize = oldSpace.getMaxSize();
            //判断
            if (totalSize >= maxSize) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "空间容量不足");
            }
        }
        // 判断是新增还是删除
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新，校验图片是否存在
        if (pictureId != null) {
            //获取图片对象
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员才可编辑图片
            // 改为使用统一的权限校验
            // if (!oldPicture.getId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            //    throw new BusinessException(ErrorCode.NO_AUTH, "无权限");
            // }
            //如果是更新图片，需要校验更新时传递的 spaceId 和已有图片的 spaceId 是否一致。如果更新时未传递 spaceId，则复用原有图片的 spaceId
            //如果没传入spaceId,则复用原有图片的 spaceId (兼容公共图库)
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                //传入的spaceId,必须与原图片的空间id一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        // 上传图片，得到图片信息
        // 按照用户 id 划分目录
        // 之前是按用户划分图片上传目录的，现在如果有 spaceId，可以按照空间来划分图片上传目录
        String uploadPathPrefix;
        if (spaceId == null) {
            //如果空间id为空则传入公共图库目录
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            //如果空间id不为空,按照每个空间id划分目录
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        //根据inputSource的类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        // 上传图片返回返回上传图片的返回结果
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);

        // 构造要入库的图片信息
        Picture picture = new Picture();
        //设置spaceId 空间id字段
        picture.setSpaceId(spaceId);
        //设置文件地址
        picture.setUrl(uploadPictureResult.getUrl());
        //设置压缩图字段
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        //设置以图搜图字段
        picture.setJpgOrPngUrl(uploadPictureResult.getJpgOrPngUrl());
        //设置颜色值字段
        picture.setPicColor(uploadPictureResult.getPicColor());
        //支持外层传递图片名称
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        //补充审核参数
        fillReviewParams(picture, loginUser);
        // 操作数据库
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        //开启事务
        Long finalSpaceId = spaceId;
        //开启编程式事务
        transactionTemplate.execute(status -> {
            //保存数据
            boolean result = this.saveOrUpdate(picture);
            //排除异常
            ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "图片上传失败，数据库操作失败");
            //更新空间额度
            if (finalSpaceId != null) {
                //更新空间的使用额度
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId).setSql("totalSize = totalSize + " + picture.getPicSize()).setSql("totalCount = totalCount + 1").update();
                ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR, "额度更新失败");
            }
            return picture;
        });

        return PictureVO.objToVo(picture);
    }

    /**
     * 返回照片查询请求体
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        //添加查询字段
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        //开始编辑时间
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        //结束编辑时间
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        //获取到图片主色调

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        //模糊查询
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        //指定查询
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        //增加查询字段
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        //增加查询时间过滤图片 大于等于起始编辑时间的图片 且同时小于等于终止编辑时间的字段
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        //增加的空间id字段
        //是否只查询字段为空 如果nullSpaceId为true则
        if (nullSpaceId) {
            //如果要查询的是 spaceId就不设置
            queryWrapper.isNull(true, "spaceId");
        } else {
            queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        }
        // JSON 数组查询
        // sql 语句类似 tags like "%\"Java\"%"
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取单个脱敏后的图片信息
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVo(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest: 图片审核请求类
     * @param loginUser:            当前用户
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //获取图片id
        Long id = pictureReviewRequest.getId();
        //获取审核状态
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        //获取审核状态枚举类
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        //判空
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空或当前图片审核状态为待审核");
        }
        //判断图片是否存在
        Picture oldPicture = this.getById(id);
        //如果图片不存在直接抛出异常 不再向下执行
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NULL_ERROR, "图片不存在");
        //如果图片已经是前端传入状态的[通过/拒绝]不需要重复审核
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        //如果数据库图片不是审核状态则更新审核状态
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "数据库操作失败");
    }

    /**
     * 此函数的逻辑是将传来的分页信息脱敏
     * <p>
     * 优化点:
     * 不针对每条数据都查询一次用户,
     * 先获取到要查询的用户id列表,
     * 只发送一次查询请求,再将查到的值设置到图片对象中
     *
     * @param picturePage: 图片分页类
     * @param request:     前端请求
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        //1、将查询到的分页信息提取
        List<Picture> pictureList = picturePage.getRecords();
        //2、新创建脱敏图片返回体
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        // 如果传来的分页信息为空则返回空的脱敏Page
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        //将对象列表脱敏
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        //3、取出用户ID 无重复用户ID set集合
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        //4、根据用户ID 查询到用户集合
        List<User> usersListByIdSet = userService.listByIds(userIdSet);
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = usersListByIdSet.stream().collect(Collectors.groupingBy(User::getId));
        //5、填充信息到脱敏后的用户信息
        for (PictureVO pictureVO : pictureVOList) {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            //将用户信息填充
            pictureVO.setUser(userService.getUserVo(user));
        }
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 设置审核状态为通过
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        //如果为管理员则自动过审
        if (userService.isAdmin(loginUser)) {
            //管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动过审");
        } else {
            //如果非管理员则 创建或编辑都要改为待审核状态
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 必应:批量抓取和创建图片
     *
     * @param pictureUploadByBatchRequest:图片批量添加请求体
     * @param loginUser:                            登录用户【指定管理员】
     * @return 成功创建的图片数
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 获取搜索关键词
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 获取图片数量
        Integer count = pictureUploadByBatchRequest.getCount();
        //限制抓取图片最大数量为30张
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        //名称前缀默认等于搜索关键词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            searchText = namePrefix;
        }
        // 抓取内容
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        //创建DOM结点
        Document document;
        //填充dom结点
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "获取页面失败");
        }
        //解析内容
        Element div = document.getElementsByClass("dgControl").first();
        //判空
        if (ObjUtil.isEmpty(div)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        //遍历元素、依次处理上传图片
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过：{}", fileUrl);
                continue;
            }
            //处理图片的地址，防止转移或者和对象储存冲突的问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            //上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            //设置url 上传图片为Url上传
            pictureUploadRequest.setFileUrl(fileUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            //执行url上传
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 百度图库获取图片
     *
     * @param pictureUploadByBatchRequest:图片批量添加请求体
     * @param loginUser:登录用户【指定管理员】
     * // todo 百度批量搜图报错
     * @return
     */
    @Override
    public Integer uploadPictureByBatchInBaiDu(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 获取搜索关键词
        String searchText = pictureUploadByBatchRequest.getSearchText();
        //名称前缀默认等于搜索关键词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            searchText = namePrefix;
        }

        // 获取图片数量
        Integer count = pictureUploadByBatchRequest.getCount();

        //限制抓取图片最大数量为20张
        ThrowUtils.throwIf(count > 20, ErrorCode.PARAMS_ERROR, "最多 20 条");

        int pageSize = RandomUtil.randomInt(1, 2);
        // https://images.baidu.com/search/acjson?tn=resultjson_com&word=美女&pn=60
        String urlTemplate = "https://images.baidu.com/search/acjson?tn=resultjson_com&word=%s&pn=%s";
        String fileUrl = String.format(urlTemplate, searchText, pageSize * 30);

        //得到json数据
        String s = HttpUtil.get(fileUrl);
        //解析json数据
        JSONObject jsonObject = JSONUtil.parseObj(s);
        JSONArray list = jsonObject.getJSONArray("data");
        int size = list.size();
        if (size >= 20) {
            size = 20;
        } else {
            size = count;
        }
        //限制20条数据
        for (int i = 0; i < size; i++) {
            JSONObject res = list.get(i, JSONObject.class);
            //获取字段
            String thumbURL = res.getStr("thumbURL");
            //上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            //设置url 上传图片为Url上传
            //设置文件地址
            pictureUploadRequest.setFileUrl(thumbURL);
            //设置图片名称
            pictureUploadRequest.setPicName(namePrefix + i);
            //执行url上传
            try {
                PictureVO pictureVO = this.uploadPicture(thumbURL, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id = {}", pictureVO.getId());
            } catch (Exception e) {
                log.error("图片上传失败", e);
            }
        }
        return size;
    }

    /**
     * 删除图片
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        //判空 排除异常
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH);
        // 判断是否存在该图片
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或者管理员可删除->权限校验
        //(loginUser, oldPicture);
        //加入逻辑 如果删除的是公共图库的图片 仅仅管理员可操作并且直接删除该图片即可
        if (oldPicture.getSpaceId() == null) {
            if (Objects.equals(loginUser.getUserRole(), UserConstant.ADMIN_ROLE)) {
                // 移除图片库该图片
                boolean result = this.removeById(pictureId);
                ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "删除图片失败");
            } else if (Objects.equals(oldPicture.getUserId(), loginUser.getId())) {
                // 如果删除的是公共图库的图片普通用户仅仅能删除自己上传的图片
                // 移除图片库该图片
                boolean result = this.removeById(pictureId);
                ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "删除图片失败");
            } else {
                ThrowUtils.throwIf(false, ErrorCode.NO_AUTH, "无权限");
            }
        } else {
            // 如果删除的是私有图库的图片需要更新额度
            // 开启事务
            transactionTemplate.execute(status -> {
                // 操作数据库
                // 移除图片库该图片
                boolean result = this.removeById(pictureId);
                // 判断是否操作成功
                ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "删除图片失败");
                // 更新空间的使用额度，释放额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR, "额度更新失败");
                return true;
            });
        }

        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    /**
     * 权限校验
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        //获取图片空间id
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库仅仅管理员或当前登录的本人可操作->加入逻辑仅能删除自己上传到公共图库的图片
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH, "无权限操作该图片");
            }
        } else {
            // 私有空间/团队空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH, "无权限操作该图片");
            }
        }
    }

    /**
     * 异步清理文件
     * 清理数据库中的文件
     *
     * @param oldPicture
     */
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断此图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        //如果不止一条记录用了该图片不清理
        if (count > 1) {
            return;
        }
        //删除云存储的图片
        cosManager.deleteObject(pictureUrl);
        //删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        //如果存在缩略图则删除
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    /**
     * 编辑图片方法 解耦
     *
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和DTO进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        //将 list转为 string->标签类
        List<String> tags = pictureEditRequest.getTags();
        String tagsString = JSONUtil.toJsonStr(tags);
        picture.setTags(tagsString);
        // 数据校验->校验图片信息
        this.validPicture(picture);
        //校验此图片是否存在于数据库中
        Long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在于数据库中");
        //权限校验->仅限本人或管理员才能编辑图片->并判断是私有空间还是公共空间->已经改为注解鉴权
        //checkPictureAuth(loginUser, oldPicture);
        //补充审核参数
        this.fillReviewParams(picture, loginUser);
        if (!userService.isAdmin(loginUser) && !oldPicture.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "仅限本人或管理员才能编辑图片");
        }
        //修改数据库图片信息
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "图片编辑失效");
    }

    /**
     * 按颜色查找图片接口
     *
     * @param spaceId    : 空间ID
     * @param picColor:  图片十六进制颜色值
     * @param userLogin: 登录用户
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User userLogin) {
        //1、检验参数
        //判断该空间是否存在
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR, "请求数据为空");
        ThrowUtils.throwIf(userLogin == null, ErrorCode.NULL_ERROR);
        //2、校验空间权限
        Space space = spaceService.getById(spaceId);
        //判空
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        //设置访问权限->进本人可以访问该空间’
        if (!space.getUserId().equals(userLogin.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "没有空间访问权限");
        }
        //3、查询该空间下的所有图片
        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId).isNotNull(Picture::getPicColor).list();
        //如果没有图片,直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            //如果图片集合为空,直接返回空列表
            return new ArrayList<>();
        }
        // 将搜索颜色字符串转换为主色调
        Color targetColor = Color.decode(picColor);
        //4、计算相似度排序
        List<Picture> sortedPictureList = pictureList.stream().sorted(Comparator.comparingDouble(picture ->
                getSimilarity((Picture) picture, targetColor)
        ).reversed()).limit(12).collect(Collectors.toList());

        //5、返回结果
        //脱敏
        return sortedPictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    /**
     * 批量处理接口
     *
     * @param pictureEditByBatchRequest: 批量处理请求类
     */
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User userLogin) {
        //获取批量处理参数
        //待修改的图片id列表
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        //修改分类
        String category = pictureEditByBatchRequest.getCategory();
        //待修改的标签表
        List<String> tags = pictureEditByBatchRequest.getTags();
        //获取批量修改的命名规则
        String nameRule = pictureEditByBatchRequest.getNameRule();
        //1、校验参数
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.NULL_ERROR, "请求数据为空");
        ThrowUtils.throwIf(spaceId == null, ErrorCode.NULL_ERROR, "空间不存在");
        ThrowUtils.throwIf(userLogin == null, ErrorCode.NO_AUTH, "请登录");
        //获取空间
        Space oldSpace = spaceService.getById(spaceId);
        //校验空间是否存在
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.SYSTEM_ERROR, "空间不存在");
        //校验用户是否有访问权限->限制仅仅本人有访问权限
        if (!oldSpace.getUserId().equals(userLogin.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "没有权限");
        }
        //2、查询id列表中的图片
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId) //选择需要查询的字段->查两个索引字段
                .eq(Picture::getSpaceId, spaceId) //查询指定的空间
                .in(Picture::getId, pictureIdList) //查询id列表
                .list();

        //3、查询到图片后修改图片的分类和标签字段
        for (Picture picture : pictureList) {
            //获取数据库图片的标签字段 和 分类字段
            String tagsString = picture.getTags();
            String categoryString = picture.getCategory();
            //判断传入的标签列表是否为空
            if (CollUtil.isNotEmpty(tags)) {
                //如果为空就不处理
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
            if (StrUtil.isNotEmpty(category)) {
                //如果为空就不处理
                picture.setCategory(category);
            }
        }
        //更新命名规则
        fillPictureWithNameRule(pictureList, nameRule);
        //批量跟新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "数据库操作失败");
    }

    /**
     * 新增私有方法补充命名规则
     *
     * @param pictureList:图片列表
     * @param nameRule:传入的命名规则
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        //判空
        if (CollUtil.isEmpty(pictureList) || StrUtil.isEmpty(nameRule)) {
            return;
        }
        long count = 1;

        try {
            for (Picture picture : pictureList) {
                String nameRuleNew = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(nameRuleNew);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "名称解析错误");
        }
    }

    /**
     * 计算图片颜色与目标颜色的相似度
     *
     * @param picture     图片对象
     * @param targetColor 目标颜色
     * @return 相似度（如果图片没有主色调，返回 Double.MIN_VALUE）
     */
    private double getSimilarity(Picture picture, Color targetColor) {
        String picColor1 = picture.getPicColor();
        // 没有主色调的图片排在最后
        if (StrUtil.isEmpty(picColor1)) {
            return Double.MIN_VALUE;
        }
        try {
            // 将十六进制颜色值解析为 Color 对象
            Color pictureColor = Color.decode(picColor1);
            // 计算相似度
            return ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
        } catch (NumberFormatException e) {
            // 处理无效颜色值
            System.err.println("Invalid color format: " + picColor1);
            return Double.MIN_VALUE;
        }
    }

    /**
     * AL扩图请求接口
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        //从数据库查寻该图片是否存在
        Picture picture = this.getById(pictureId);
        //判断照片是否存在
        Optional.ofNullable(picture).orElseThrow(() -> new BusinessException(ErrorCode.NULL_ERROR, "图片未查到"));
        // 权限校验
        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        //对象复制
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * AI图片生成视频请求接口
     *
     * @param createPictureOutMp4TaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutMp4askResponse createPictureOutMp4Task(CreatePictureOutMp4TaskRequest createPictureOutMp4TaskRequest, User loginUser) {
        //获取图片id
        final Long pictureId = createPictureOutMp4TaskRequest.getPictureId();
        final String prompt = createPictureOutMp4TaskRequest.getPrompt();
        //判断数据库是否存在该图片
        Picture picture = this.getById(pictureId);
        //判空
        ThrowUtils.throwIf(ObjUtil.isEmpty(picture), ErrorCode.NULL_ERROR, "图片不存在");
        //权限校验
        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutMp4TaskRequest createOutMp4TaskRequest = new CreateOutMp4TaskRequest();
        CreateOutMp4TaskRequest.Input input = new CreateOutMp4TaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        input.setPrompt(prompt);
        createOutMp4TaskRequest.setInput(input);
        //BeanUtil.copyProperties(createPictureOutMp4TaskRequest, createOutMp4TaskRequest);
        // 手动复制嵌套对象
        if (createPictureOutMp4TaskRequest.getParameters() != null) {
            CreateOutMp4TaskRequest.Parameters parameters =
                    new CreateOutMp4TaskRequest.Parameters();
            BeanUtil.copyProperties(
                    createPictureOutMp4TaskRequest.getParameters(),
                    parameters
            );
            createOutMp4TaskRequest.setParameters(parameters);
        }
        //创建任务
        return aiPictureToMp4.createOutMp4askResponse(createOutMp4TaskRequest);
    }

    /**
     * 百度抓取图片测试方法
     *
     * @param args
     */
    public static void main(String[] args) {
        /**
         * tn=resultjson_com：必带的参数
         * word：搜索关键词
         * pn：分页数，传入30的倍数，第一次为30，第二次为60，以此内推
         */
        String urlTemplate = "https://images.baidu.com/search/acjson?tn=resultjson_com&word=%s&pn=%s";
        String queryTxt = "壁纸";
        //  这个for循环，模拟了查询第一页和第二页的数据
        for (int i = 1; i <= 2; i++) {
            String url = String.format(urlTemplate, queryTxt, i * 30);
            String s = HttpUtil.get(url);
            JSONObject jsonObject = JSONUtil.parseObj(s);
            JSONArray list = jsonObject.getJSONArray("data");
            System.out.println("查找到的图片的总数" + list.size());
            int index = 1;
            System.out.println("第" + i + "次查询 ====");
            for (int j = 0; j < list.size(); j++) {
                JSONObject res = list.get(j, JSONObject.class);
                String thumbURL = res.getStr("thumbURL");
                System.out.println(index + "=======" + thumbURL);
                index++;
            }
        }
    }

}


